//
//  TencentWX.m
//  Unity-iPhone
//
//  Created by YunQue on 2025/4/25.
//

#import <Foundation/Foundation.h>
#import "TencentWX.h"
#import "GameHelper.h"

@implementation TencentWX

static TencentWX *instance;

+(instancetype) Instance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TencentWX alloc] init];
    });
    return instance;
}

-(void) Init
{
    [WXApi registerApp:@"wxcc165bd58a6d04a0" universalLink:@"https://test.lcqf.net/ulink/"];
    
    NSLog(@"微信初始化成功！");
}

-(void) Login
{
    if([WXApi isWXAppInstalled])
    {
        SendAuthReq* req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"wechat_Huang";
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
    }
    else
    {
        [self SetupAlertController];
    }
}

-(void)Logout
{
    
}

-(BOOL)CheckAuthorVaild
{
    NSUserDefaults *login = [NSUserDefaults standardUserDefaults];
    NSString *str = [login objectForKey:@"WXcache"];
    if(str == nil || [str  isEqual: @""])
    {
        NSLog(@"本地无储存RefreshToken");
        return false;
    }
    
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@",@"wxcc165bd58a6d04a0",str];
    
    BOOL __block isVaild = false;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(data)
        {
            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            if([jsonString containsString:@"errcode"])
            {
                NSLog(@"授权无效，需要重新授权！");
                isVaild = false;
            }
            else
            {
                NSLog(@"授权有效，不需要重新授权！");
                isVaild = true;
            }
        }
        dispatch_semaphore_signal(semaphore);
    }];
    
    [task resume];
    
    //等待线程阻塞
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return isVaild;
}

-(NSString *)GetAuthor
{
    NSUserDefaults *login = [NSUserDefaults standardUserDefaults];
    NSString *str = [login objectForKey:@"WXcache"];
    if(str == nil || [str  isEqual: @""])
    {
        NSLog(@"本地无储存RefreshToken");
        return nil;
    }
    
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@",@"wxcc165bd58a6d04a0",str];
    
    NSData __block *jsonData;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(data)
        {
            jsonData = data;
        }
        dispatch_semaphore_signal(semaphore);
    }];
    
    [task resume];
    
    //等待线程阻塞
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return [self SetSelfData:jsonData];
}

-(NSString*)SetSelfData:(NSData*)data
{
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSString* token = [dic objectForKey:@"access_token"];
    NSString* openid = [dic objectForKey:@"openid"];
    NSString* refreshtoken = [dic objectForKey:@"refresh_token"];
    NSString* expires = [dic objectForKey:@"expires_in"];
    NSString* unionid = [self GetUnionid:openid token:token];
    NSString* paytoken = @"";
    NSString* pf = @"";
    NSString* pfkey = @"";
    NSString* expirestime = @"";
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                openid,@"openid",
                                token,@"token",
                                unionid,@"unionid",
                                refreshtoken,@"refreshtoken",
                                expires,@"expires",
                                paytoken,@"paytoken",
                                pf,@"pf",
                                pfkey,@"pfkey",
                                expirestime,@"expirestime",
                                nil];
    
    NSUserDefaults *login = [NSUserDefaults standardUserDefaults];
    [login setObject:refreshtoken forKey:@"WXcache"];
    [login synchronize];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"ios wx 请求票据成功！： %@",jsonString);
    return jsonString;
}

-(NSString*)GetUnionid:(NSString*)openid token:(NSString*)token
{
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openid];
    
    NSData __block *jsonData;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(data)
        {
            jsonData = data;
        }
        dispatch_semaphore_signal(semaphore);
    }];
    
    [task resume];
    
    //等待线程阻塞
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSString* unionid = [dic objectForKey:@"unionid"];
    return unionid;
}

-(void) SetupAlertController
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装维修客户端" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionConfirm];
}

//微信向第三方应用请求回调
-(void) onReq:(BaseReq *)req
{
    
}

//第三方应用向微信请求回调
-(void) onResp:(BaseResp *)resp
{
    SendAuthResp *aresp = (SendAuthResp *)resp;
    if(aresp.errCode == WXSuccess)
    {
        NSLog(@"登陆成功，code:%@",aresp.code);
        [self getAccess_token:aresp.code];
    }
    else if(aresp.errCode == WXErrCodeUserCancel)
    {
        NSLog(@"用户取消登陆！");
        _SendPlatformMessageToUnity(PLATFORM_MSG_WXLOGINCALLBACK, 2,0,0, @"",@"",@"");
    }
    else if(aresp.errCode == WXErrCodeAuthDeny)
    {
        NSLog(@"用户登陆失败！");
        _SendPlatformMessageToUnity(PLATFORM_MSG_WXLOGINCALLBACK, 1,0,0, @"",@"",@"");
    }
    else
    {
        NSLog(@"errCode = %d",aresp.errCode);
        _SendPlatformMessageToUnity(PLATFORM_MSG_WXLOGINCALLBACK, 1,0,0, @"",@"",@"");
    }
}

-(void)getAccess_token:(NSString *)code
{
    NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wxcc165bd58a6d04a0",@"fd30a6deb2925263d1ceac86b3276d6a",code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneURL = [NSURL URLWithString:url];
        NSString *zoneSTr = [NSString stringWithContentsOfURL:zoneURL encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneSTr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if(data)
            {
                NSString* jsonString = [self SetSelfData:data];
                _SendPlatformMessageToUnity(PLATFORM_MSG_WXLOGINCALLBACK, 0,0,0, jsonString,@"",@"");
            }
        });
    });
}
@end
